<template>
  <div class="screen-container">
    <!-- 添加标题 -->
    <div class="screen-title">智慧房屋数据平台</div>

    <!-- 顶部统计数据 -->
    <div class="header-stats">
      <div class="stat-item">
        <div class="stat-title">房屋总数</div>
        <div class="stat-value">{{stats.totalHouses}}</div>
      </div>
      <div class="stat-item">
        <div class="stat-title">一般隐患房屋数</div>
        <div class="stat-value">{{stats.normalRiskHouses}}</div>
      </div>
      <div class="stat-item">
        <div class="stat-title">严重隐患房屋数</div>
        <div class="stat-value">{{stats.highRiskHouses}}</div>
      </div>
      <div class="stat-item">
        <div class="stat-title">房屋档案数</div>
        <div class="stat-value">{{stats.houseFiles}}</div>
      </div>
      <div class="stat-item">
        <div class="stat-title">设备告警数</div>
        <div class="stat-value">{{stats.deviceAlerts}}</div>
      </div>
    </div>

    <!-- 左侧面板 -->
    <div class="left-panel">
      <div class="chart-card">
        <div class="chart-title">房屋隐患占比图</div>
        <div class="chart-content" ref="riskPieChart"></div>
      </div>
      <div class="chart-card">
        <div class="chart-title">房屋档案TOP5</div>
        <div class="chart-content" ref="houseTop5Chart"></div>
      </div>
      <div class="chart-card">
        <div class="chart-title">设备类型分布</div>
        <div class="chart-content" ref="deviceTypeChart"></div>
      </div>
    </div>

    <!-- 右侧面板 -->
    <div class="right-panel">
      <div class="chart-card">
        <div class="chart-title">设备告警次数TOP5</div>
        <div class="chart-content" ref="alertTop5Chart"></div>
      </div>
      <div class="chart-card">
        <div class="chart-title">房屋类型占比图</div>
        <div class="chart-content" ref="houseTypeChart"></div>
      </div>
      <div class="chart-card">
        <div class="chart-title">近期房屋排查记录</div>
        <div class="chart-content recent-records">
          <div v-for="(record, index) in recentRecords" :key="index" class="record-item">
            <div class="record-left">
              <div class="record-time">{{record.time}}</div>
              <div class="record-address">{{record.address}}</div>
            </div>
            <div class="record-status" :class="record.status">{{record.result}}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 3D地图 -->
    <div class="map-container">
      <!-- <baidu-map-g-l
        ref="baiduMap"
        class="map"
        :longitude="116.404"
        :latitude="39.915"
        :zoom="18"
        :editable="false"
        :theme="currentTheme"
        :viewOptions="{
          tilt: 70,
          heading: 45,
          showControls: true
        }"
        @marker-move="handleMarkerMove"
        @map-ready="handleMapReady"
      ></baidu-map-g-l> -->
      <a-map-g-l
        ref="aMap"
        class="map"
        :longitude="116.404"
        :latitude="39.915"
        :zoom="25"
        :editable="false"
        :viewOptions="{
          pitch: 60,
          rotation: 45,
          showControls: true
        }"
        @marker-move="handleMarkerMove"
        @map-ready="handleMapReady"
      ></a-map-g-l>
      
      <!-- 定位到最近点位按钮 -->
      <div class="locate-btn" @click="findNearestPoint">
        <i class="el-icon-location"></i>
      </div>
    </div>
  </div>
</template>

<script>
import BaiduMapGL from '@/components/BaiduMapGL'
import AMapGL from '@/components/AMapGL'
import * as echarts from 'echarts'
import { getScreenStats, getHouseRiskDistribution, getDeviceTypeDistribution, getHouseDocumentTop5, getDeviceAlertTop5, getHouseTypeDistribution, getRecentInspections, getHouseLocations, getDeviceLocations } from "@/api/screen/index";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: 'Map',
  components: {
    BaiduMapGL,
    AMapGL
  },
  dicts: ['safety_danger_type'],
  data() {
    return {
      map: null,
      currentTheme: 'dark',
      charts: {
        riskPie: null,
        houseTop5: null,
        alertTop5: null,
        houseType: null,
        deviceType: null
      },
      stats: {
        totalHouses: 0,
        normalRiskHouses: 0,
        highRiskHouses: 0,
        houseFiles: 0,
        deviceAlerts: 0
      },
      chartData: {
        riskPie: [],
        houseTop5: {
          names: [],
          values: []
        },
        deviceType: [],
        alertTop5: {
          names: [],
          values: []
        },
        houseType: []
      },
      recentRecords: [],
      // 安全隐患类型字典
      safetyDangerOptions: [],
      markers: {
        houses: [],
        devices: []
      },
      markerIcons: {
        house: require('@/assets/logo/logo.png'),
        device: require('@/assets/images/device_marker.png')
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
      this.getStats()
      this.getLeftPanelData()
      this.getRightPanelData()
      // 添加窗口大小变化监听
      window.addEventListener('resize', this.handleResize)
    })
  },
  created() {
    this.getStats();
    this.getLeftPanelData();
    this.getRightPanelData();
  },
  methods: {
    handleMarkerMove(position) {
      console.log('标记点移动到：', position)
    },
    handleMapReady(map) {
      this.map = map
      console.log('地图加载完成')
      this.initMapMarkers()
    },
    // 计算两点之间的距离
    calculateDistance(point1, point2) {
      return AMap.GeometryUtil.distance(
        [point1.lng, point1.lat],
        [point2.lng, point2.lat]
      ) / 1000; // 转换为公里
    },
    // 找到最近的点位并设置为地图中心
    async findNearestPoint() {
      try {
        // 获取房屋和设备位置数据
        const [houseRes, deviceRes] = await Promise.all([
          getHouseLocations(),
          getDeviceLocations()
        ]);
        
        let allPoints = [];
        if (houseRes.code === 200 && houseRes.data) {
          allPoints = allPoints.concat(houseRes.data.map(house => ({
            lat: house.latitude,
            lng: house.longitude,
            type: 'house',
            name: house.houseName
          })));
        }
        if (deviceRes.code === 200 && deviceRes.data) {
          allPoints = allPoints.concat(deviceRes.data.map(device => ({
            lat: device.latitude,
            lng: device.longitude,
            type: 'device',
            name: device.deviceName
          })));
        }

        if (allPoints.length === 0) return;

        // 获取当前地图中心点
        const center = this.map.getCenter();
        const currentCenter = {
          lat: center.lat,
          lng: center.lng
        };

        // 计算最近的点
        let nearestPoint = allPoints[0];
        let minDistance = this.calculateDistance(currentCenter, nearestPoint);

        allPoints.forEach(point => {
          const distance = this.calculateDistance(currentCenter, point);
          if (distance < minDistance) {
            minDistance = distance;
            nearestPoint = point;
          }
        });

        // 设置地图中心为最近的点
        this.map.setCenter([nearestPoint.lng, nearestPoint.lat]);
        
        // 可以添加一个提示
        //this.$message.success(`已将地图中心设置为最近的${nearestPoint.type === 'house' ? '房屋' : '设备'}：${nearestPoint.name}`);
      } catch (error) {
        console.error('查找最近点位失败:', error);
        this.$message.error('查找最近点位失败');
      }
    },
    toggleTheme() {
      this.currentTheme = this.currentTheme === 'normal' ? 'dark' : 'normal'
    },
    initCharts() {
      // 初始化房屋隐患占比图
      this.charts.riskPie = echarts.init(this.$refs.riskPieChart)
      this.charts.riskPie.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
          backgroundColor: 'rgba(17, 53, 73, 0.9)',
          borderColor: '#0288D1',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: 'middle',
          itemWidth: 15,
          itemHeight: 15,
          itemGap: 16,
          textStyle: {
            color: '#B0BEC5',
            fontSize: 14,
            padding: [5, 0, 5, 0]
          }
        },
        series: [{
          type: 'pie',
          radius: ['55%', '75%'],
          center: ['35%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#102338',
            borderWidth: 1
          },
          label: {
            show: true,
            position: 'inside',
            formatter: '{d}%',
            fontSize: 16,
            fontWeight: 'bold',
            color: '#fff',
            textShadow: '0 1px 2px rgba(0,0,0,0.5)'
          },
          emphasis: {
            label: {
              fontSize: 16,
              fontWeight: 'bold'
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          data: [
            { value: 1193, name: '正常房屋', itemStyle: { color: '#0288D1' } },
            { value: 45, name: '一般隐患', itemStyle: { color: '#FFA726' } },
            { value: 12, name: '严重隐患', itemStyle: { color: '#EF5350' } }
          ]
        }]
      })

      // 初始化设备类型分布图
      this.charts.deviceType = echarts.init(this.$refs.deviceTypeChart)
      this.charts.deviceType.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
          backgroundColor: 'rgba(17, 53, 73, 0.9)',
          borderColor: '#0288D1',
          textStyle: {
            color: '#fff'
          }
        },
        series: [{
          type: 'pie',
          radius: ['60%', '80%'],
          center: ['50%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#102338',
            borderWidth: 1
          },
          label: {
            show: true,
            position: 'inside',
            formatter: '{b}\n{d}%',
            fontSize: 14,
            fontWeight: 'bold',
            color: '#fff',
            textShadow: '0 1px 2px rgba(0,0,0,0.5)'
          },
          emphasis: {
            label: {
              fontSize: 16,
              fontWeight: 'bold'
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          data: [
            { value: 280, name: '烟感器', itemStyle: { color: '#4FC3F7' } },
            { value: 250, name: '温感器', itemStyle: { color: '#81C784' } },
            { value: 220, name: '监控', itemStyle: { color: '#7986CB' } },
            { value: 200, name: '门禁', itemStyle: { color: '#FFB74D' } },
            { value: 180, name: '水表', itemStyle: { color: '#BA68C8' } },
            { value: 150, name: '电表', itemStyle: { color: '#F06292' } }
          ]
        }]
      })

      // 初始化房屋档案TOP5
      this.charts.houseTop5 = echarts.init(this.$refs.houseTop5Chart)
      this.charts.houseTop5.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(17, 53, 73, 0.9)',
          borderColor: '#0288D1',
          textStyle: {
            color: '#fff'
          }
        },
        grid: {
          top: '5%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          minInterval: 1,
          axisLabel: {
            color: '#B0BEC5',
            fontSize: 12,
            formatter: function(value) {
              return Math.floor(value);
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#0288D1',
              width: 1
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(2, 136, 209, 0.1)',
              type: 'dashed'
            }
          }
        },
        yAxis: {
          type: 'category',
          data: [
            '海淀区丰德大厦A座',
            '朝阳区望京科技大厦',
            '西城区金融中心B座',
            '东城区东环广场',
            '丰台区丽泽金融中心'
          ],
          axisLine: {
            show: true,
            lineStyle: {
              color: '#0288D1',
              width: 1
            }
          },
          axisLabel: {
            color: '#B0BEC5',
            fontSize: 12,
            margin: 16,
            width: 150,
            overflow: 'truncate'
          }
        },
        series: [{
          name: '档案数量',
          type: 'bar',
          barWidth: '40%',
          data: [156, 142, 128, 115, 98],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#01579B' },
              { offset: 1, color: '#0288D1' }
            ]),
            borderRadius: [0, 4, 4, 0]
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      })

      // 初始化设备告警TOP5
      this.charts.alertTop5 = echarts.init(this.$refs.alertTop5Chart)
      this.charts.alertTop5.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(17, 53, 73, 0.9)',
          borderColor: '#0288D1',
          textStyle: {
            color: '#fff'
          }
        },
        grid: {
          top: '5%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['烟感器', '温感器', '监控', '门禁', '水表'],
          axisLabel: {
            color: '#B0BEC5',
            fontSize: 12,
            margin: 16
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#0288D1',
              width: 1
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#B0BEC5',
            fontSize: 12
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#0288D1',
              width: 1
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(2, 136, 209, 0.1)',
              type: 'dashed'
            }
          }
        },
        series: [{
          data: [5, 4, 3, 2, 1],
          type: 'bar',
          barWidth: '40%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#0288D1' },
              { offset: 1, color: '#01579B' }
            ]),
            borderRadius: [4, 4, 0, 0]
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      })

      // 初始化房屋类型占比图
      this.charts.houseType = echarts.init(this.$refs.houseTypeChart)
      this.charts.houseType.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
          backgroundColor: 'rgba(17, 53, 73, 0.9)',
          borderColor: '#0288D1',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          orient: 'vertical',
          right: '2%',
          top: 'middle',
          itemWidth: 15,
          itemHeight: 15,
          itemGap: 16,
          textStyle: {
            color: '#B0BEC5',
            fontSize: 14,
            padding: [5, 0, 5, 0]
          }
        },
        series: [{
          type: 'pie',
          radius: ['55%', '75%'],
          center: ['35%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#102338',
            borderWidth: 1
          },
          label: {
            show: true,
            position: 'inside',
            formatter: '{d}%',
            fontSize: 16,
            fontWeight: 'bold',
            color: '#fff',
            textShadow: '0 1px 2px rgba(0,0,0,0.5)'
          },
          emphasis: {
            label: {
              fontSize: 16,
              fontWeight: 'bold'
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          data: [
            { value: 520, name: '住宅', itemStyle: { color: '#4FC3F7' } },
            { value: 320, name: '商业', itemStyle: { color: '#81C784' } },
            { value: 240, name: '办公', itemStyle: { color: '#7986CB' } },
            { value: 170, name: '其他', itemStyle: { color: '#9575CD' } }
          ]
        }]
      })
    },
    // 添加处理窗口大小变化的方法
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize()
        }
      })
    },
    // 在切换全屏时也触发重绘
    toggleFullScreen() {
      const element = document.documentElement
      if (!document.fullscreenElement) {
        element.requestFullscreen()
      } else {
        document.exitFullscreen()
      }
      // 等待全屏切换完成后重绘图表
      setTimeout(() => {
        this.handleResize()
      }, 100)
    },
    // 获取统计数据
    async getStats() {
      try {
        const res = await getScreenStats()
        if (res.code === 200) {
          this.stats = res.data
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    },
    // 获取左侧图表数据
    async getLeftPanelData() {
      try {
        // 并行获取三个图表的数据
        const [riskRes, top5Res, deviceRes] = await Promise.all([
          getHouseRiskDistribution(),
          getHouseDocumentTop5(),
          getDeviceTypeDistribution()
        ]);

        // 更新房屋隐患占比图数据
        if (riskRes.code === 200) {
          this.chartData.riskPie = [
            { value: this.stats.totalHouses - this.stats.normalRiskHouses - this.stats.highRiskHouses, 
              name: '正常房屋', 
              itemStyle: { color: '#0288D1' } 
            },
            { value: this.stats.normalRiskHouses, 
              name: '一般隐患', 
              itemStyle: { color: '#FFA726' } 
            },
            { value: this.stats.highRiskHouses, 
              name: '严重隐患', 
              itemStyle: { color: '#EF5350' } 
            }
          ];
          this.updateRiskPieChart();
        }

        // 更新房屋档案TOP5数据
        if (top5Res.code === 200) {
          const top5Data = top5Res.data;
          this.chartData.houseTop5.names = top5Data.map(item => item.name);
          this.chartData.houseTop5.values = top5Data.map(item => item.value);
          this.updateHouseTop5Chart();
        }

        // 更新设备类型分布数据
        if (deviceRes.code === 200) {
          this.chartData.deviceType = deviceRes.data.map(item => ({
            value: item.value,
            name: item.name,
            itemStyle: { 
              color: this.getDeviceTypeColor(item.name)
            }
          }));
          this.updateDeviceTypeChart();
        }
      } catch (error) {
        console.error('获取左侧面板数据失败:', error);
      }
    },
    // 获取设备类型对应的颜色
    getDeviceTypeColor(type) {
      const colorMap = {
        '烟感器': '#4FC3F7',
        '温感器': '#81C784',
        '监控': '#7986CB',
        '门禁': '#FFB74D',
        '水表': '#BA68C8',
        '电表': '#F06292'
      };
      return colorMap[type] || '#4FC3F7';
    },
    // 更新房屋隐患占比图
    updateRiskPieChart() {
      if (!this.charts.riskPie) return;
      
      this.charts.riskPie.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
          backgroundColor: 'rgba(17, 53, 73, 0.9)',
          borderColor: '#0288D1',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: 'middle',
          itemWidth: 15,
          itemHeight: 15,
          itemGap: 16,
          textStyle: {
            color: '#B0BEC5',
            fontSize: 14,
            padding: [5, 0, 5, 0]
          }
        },
        series: [{
          type: 'pie',
          radius: ['55%', '75%'],
          center: ['35%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#102338',
            borderWidth: 1
          },
          label: {
            show: true,
            position: 'inside',
            formatter: '{d}%',
            fontSize: 16,
            fontWeight: 'bold',
            color: '#fff',
            textShadow: '0 1px 2px rgba(0,0,0,0.5)'
          },
          emphasis: {
            label: {
              fontSize: 16,
              fontWeight: 'bold'
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          data: this.chartData.riskPie
        }]
      });
    },
    // 更新房屋档案TOP5图表
    updateHouseTop5Chart() {
      if (!this.charts.houseTop5) return;
      
      this.charts.houseTop5.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(17, 53, 73, 0.9)',
          borderColor: '#0288D1',
          textStyle: {
            color: '#fff'
          }
        },
        grid: {
          top: '5%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          minInterval: 1,
          axisLabel: {
            color: '#B0BEC5',
            fontSize: 12,
            formatter: function(value) {
              return Math.floor(value);
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#0288D1',
              width: 1
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(2, 136, 209, 0.1)',
              type: 'dashed'
            }
          }
        },
        yAxis: {
          type: 'category',
          data: this.chartData.houseTop5.names,
          axisLine: {
            show: true,
            lineStyle: {
              color: '#0288D1',
              width: 1
            }
          },
          axisLabel: {
            color: '#B0BEC5',
            fontSize: 12,
            margin: 16,
            width: 150,
            overflow: 'truncate'
          }
        },
        series: [{
          name: '档案数量',
          type: 'bar',
          barWidth: '40%',
          data: this.chartData.houseTop5.values,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#01579B' },
              { offset: 1, color: '#0288D1' }
            ]),
            borderRadius: [0, 4, 4, 0]
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      });
    },
    // 更新设备类型分布图
    updateDeviceTypeChart() {
      if (!this.charts.deviceType) return;
      
      this.charts.deviceType.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
          backgroundColor: 'rgba(17, 53, 73, 0.9)',
          borderColor: '#0288D1',
          textStyle: {
            color: '#fff'
          }
        },
        series: [{
          type: 'pie',
          radius: ['60%', '80%'],
          center: ['50%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#102338',
            borderWidth: 1
          },
          label: {
            show: true,
            position: 'inside',
            formatter: '{b}\n{d}%',
            fontSize: 14,
            fontWeight: 'bold',
            color: '#fff',
            textShadow: '0 1px 2px rgba(0,0,0,0.5)'
          },
          emphasis: {
            label: {
              fontSize: 16,
              fontWeight: 'bold'
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          data: this.chartData.deviceType
        }]
      });
    },
    // 获取右侧面板数据
    async getRightPanelData() {
      try {
        // 并行获取三个图表的数据
        const [alertRes, typeRes, inspectionRes] = await Promise.all([
          getDeviceAlertTop5(),
          getHouseTypeDistribution(),
          getRecentInspections()
        ]);

        // 更新设备告警TOP5数据
        if (alertRes.code === 200) {
          const alertData = alertRes.data;
          this.chartData.alertTop5.names = alertData.map(item => item.name);
          this.chartData.alertTop5.values = alertData.map(item => item.value);
          this.updateAlertTop5Chart();
        }

        // 更新房屋类型分布数据
        if (typeRes.code === 200) {
          this.chartData.houseType = typeRes.data.map(item => ({
            value: item.value,
            name: item.name,
            itemStyle: { 
              color: this.getHouseTypeColor(item.name)
            }
          }));
          this.updateHouseTypeChart();
        }

        // 更新近期排查记录
        if (inspectionRes.code === 200) {
          this.recentRecords = inspectionRes.data.map(item => {
            return {
              time: this.parseTime(item.inspectTime),
              address: item.houseAddress,
              status: item.resultClass || 'info',
              result: this.selectDictLabel(this.dict.type.safety_danger_type, item.checkResult)
            };
          });
          console.log(this.recentRecords);
        }
      } catch (error) {
        console.error('获取右侧面板数据失败:', error);
      }
    },
    // 获取房屋类型对应的颜色
    getHouseTypeColor(type) {
      const colorMap = {
        '住宅': '#4FC3F7',
        '商业': '#81C784',
        '办公': '#7986CB',
        '其他': '#9575CD'
      };
      return colorMap[type] || '#4FC3F7';
    },
    // 获取排查状态样式
    getInspectionStatus(riskLevel) {
      const statusMap = {
        '0': 'normal',
        '1': 'warning',
        '2': 'danger'
      };
      return statusMap[riskLevel] || 'normal';
    },
    // 获取排查状态文本
    getInspectionStatusText(riskLevel) {
      const textMap = {
        '0': '正常',
        '1': '一般隐患',
        '2': '严重隐患'
      };
      return textMap[riskLevel] || '正常';
    },
    // 更新设备告警TOP5图表
    updateAlertTop5Chart() {
      if (!this.charts.alertTop5) return;
      
      this.charts.alertTop5.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(17, 53, 73, 0.9)',
          borderColor: '#0288D1',
          textStyle: {
            color: '#fff'
          }
        },
        grid: {
          top: '5%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.chartData.alertTop5.names,
          axisLabel: {
            color: '#B0BEC5',
            fontSize: 12,
            margin: 16,
            interval: 0,
            rotate: 30
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#0288D1',
              width: 1
            }
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1,
          axisLabel: {
            color: '#B0BEC5',
            fontSize: 12,
            formatter: function(value) {
              return Math.floor(value);
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#0288D1',
              width: 1
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(2, 136, 209, 0.1)',
              type: 'dashed'
            }
          }
        },
        series: [{
          name: '告警次数',
          type: 'bar',
          barWidth: '40%',
          data: this.chartData.alertTop5.values,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#0288D1' },
              { offset: 1, color: '#01579B' }
            ]),
            borderRadius: [4, 4, 0, 0]
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      });
    },
    // 更新房屋类型占比图
    updateHouseTypeChart() {
      if (!this.charts.houseType) return;
      
      this.charts.houseType.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
          backgroundColor: 'rgba(17, 53, 73, 0.9)',
          borderColor: '#0288D1',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          orient: 'vertical',
          right: '2%',
          top: 'middle',
          itemWidth: 15,
          itemHeight: 15,
          itemGap: 16,
          textStyle: {
            color: '#B0BEC5',
            fontSize: 14,
            padding: [5, 0, 5, 0]
          }
        },
        series: [{
          type: 'pie',
          radius: ['55%', '75%'],
          center: ['35%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#102338',
            borderWidth: 1
          },
          label: {
            show: true,
            position: 'inside',
            formatter: '{d}%',
            fontSize: 16,
            fontWeight: 'bold',
            color: '#fff',
            textShadow: '0 1px 2px rgba(0,0,0,0.5)'
          },
          emphasis: {
            label: {
              fontSize: 16,
              fontWeight: 'bold'
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          data: this.chartData.houseType
        }]
      });
    },
    // 格式化时间
    parseTime(time) {
      if (!time) return '';
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 初始化地图标记
    async initMapMarkers() {
      try {
        // 并行获取房屋和设备位置数据
        const [houseRes, deviceRes] = await Promise.all([
          getHouseLocations(),
          getDeviceLocations()
        ]);

        if (houseRes.code === 200) {
          // 添加房屋标记
          this.markers.houses = houseRes.data.map(item => ({
            id: 'house_' + item.houseId,
            position: {
              lng: item.longitude,
              lat: item.latitude
            },
            icon: this.markerIcons.house,
            size: { width: 32, height: 32 },
            title: item.houseName,
            type: 'house',
            address: item.address,
            purpose: item.housePurpose,
            area: item.buildingArea,
            data: item
          }));
        }

        if (deviceRes.code === 200) {
          // 添加设备标记
          this.markers.devices = deviceRes.data.map(item => ({
            id: 'device_' + item.deviceId,
            position: {
              lng: item.longitude,
              lat: item.latitude
            },
            icon: this.markerIcons.device,
            size: { width: 24, height: 24 },
            title: item.deviceName,
            type: 'device',
            address: item.installAddress,
            purpose: item.deviceType,
            data: item
          }));
        }

        // 将所有标记添加到地图上
        this.addMarkersToMap();
      } catch (error) {
        console.error('获取标记点数据失败:', error);
      }
    },

    // 添加标记到地图
    addMarkersToMap() {
      if (!this.map) return;

      try {
        // 准备标记点数据
        const markersData = [
          ...this.markers.houses.map(marker => ({
            longitude: marker.position.lng,
            latitude: marker.position.lat,
            title: marker.title,
            type: 'house',
            icon: marker.icon,
            address: marker.data.address,
            purpose: marker.data.housePurpose,
            area: marker.data.buildingArea,
            onClick: () => this.handleMarkerClick(marker)
          })),
          ...this.markers.devices.map(marker => ({
            longitude: marker.position.lng,
            latitude: marker.position.lat,
            title: marker.title,
            type: 'device',
            icon: marker.icon,
            address: marker.data.installAddress,
            purpose: marker.data.deviceType,
            onClick: () => this.handleMarkerClick(marker)
          }))
        ];

        // 调用AMapGL组件的方法添加标记
        this.$refs.aMap.addMarkersToMap(markersData);
      } catch (error) {
        console.error('添加标记点失败:', error);
      }
    },

    // 处理标记点击事件
    handleMarkerClick(marker) {
      // 根据标记类型显示不同的信息
      if (marker.type === 'house') {
        this.$notify({
          title: marker.title,
          message: `地址：${marker.address || '暂无'}`,
          type: 'info'
        });
      } else {
        this.$notify({
          title: marker.title,
          message: `设备类型：${marker.purpose || '暂无'}`,
          type: 'info'
        });
      }
    },

    // 调整地图视图以显示所有标记
    fitMapView() {
      if (!this.map || [...this.markers.houses, ...this.markers.devices].length === 0) return;

      const points = [...this.markers.houses, ...this.markers.devices].map(
        marker => [marker.position.lng, marker.position.lat]
      );
      
      // 使用高德地图的setFitView方法自动调整视野
      this.map.setFitView();
    },
  },
  beforeDestroy() {
    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize)
  }
}
</script>

<style scoped>
.screen-container {
  width: 100%;
  height: 100vh;
  background-color: #102338;
  position: relative;
  overflow: hidden;
  color: #0288D1;
}

.screen-title {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 28px;
  font-weight: bold;
  color: #039BE5;
  z-index: 11;
  text-shadow: 0 0 15px rgba(3, 155, 229, 0.5);
  letter-spacing: 2px;
}

.header-stats {
  position: absolute;
  top: 70px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 0 50px;
  z-index: 10;
}

.stat-item {
  background: rgba(30, 85, 120, 0.65);
  border: 1px solid #039BE5;
  border-radius: 8px;
  padding: 15px 25px;
  text-align: center;
  backdrop-filter: blur(10px);
  min-width: 180px;
  box-shadow: 0 0 15px rgba(3, 155, 229, 0.25);
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 0 20px rgba(3, 155, 229, 0.3);
}

.stat-title {
  font-size: 14px;
  margin-bottom: 10px;
  opacity: 1;
  color: #E1F5FE;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  background: linear-gradient(to bottom, #03A9F4, #039BE5);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 2px 4px rgba(3, 155, 229, 0.3);
}

.left-panel,
.right-panel {
  position: absolute;
  top: 160px;
  bottom: 20px;
  width: 320px;
  z-index: 10;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.left-panel {
  left: 20px;
  gap: 15px;
}

.left-panel .chart-card:first-child {
  flex: 1;  /* 房屋隐患占比图 */
}

.left-panel .chart-card:nth-child(2) {
  flex: 1;  /* 房屋档案TOP5 */
}

.left-panel .chart-card:last-child {
  flex: 1;  /* 设备类型分布 */
}

.right-panel {
  right: 20px;
  gap: 15px;
}

.right-panel .chart-card:first-child {
  flex: 1.2;
}

.right-panel .chart-card:nth-child(2) {
  flex: 1.4;
}

.right-panel .chart-card:last-child {
  flex: 0.6;
}

.chart-card {
  flex: 1;
  background: rgba(30, 85, 120, 0.65);
  border: 1px solid #039BE5;
  border-radius: 12px;
  padding: 20px;
  backdrop-filter: blur(10px);
  box-shadow: 0 0 15px rgba(3, 155, 229, 0.25);
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 0 20px rgba(3, 155, 229, 0.3);
}

.chart-title {
  font-size: 16px;
  margin-bottom: 20px;
  padding-left: 12px;
  border-left: 4px solid #03A9F4;
  display: flex;
  align-items: center;
  position: relative;
}

.chart-title::after {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  width: 50%;
  height: 1px;
  background: linear-gradient(to right, #03A9F4, transparent);
  transform: translateY(-50%);
}

.chart-content {
  height: calc(100% - 40px);
}

.chart-content:not(.recent-records) {
  display: flex;
  align-items: center;
  justify-content: center;
}

.recent-records {
  overflow-y: auto;
  padding: 0;
}

.record-item {
  padding: 10px 20px;
  border-bottom: 1px solid rgba(3, 155, 229, 0.15);
  transition: all 0.3s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-item:hover {
  background: rgba(3, 155, 229, 0.1);
}

.record-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.record-time {
  font-size: 14px;
  color: #B3E5FC;
}

.record-address {
  font-size: 14px;
  color: #90CAF9;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.record-status {
  padding: 4px 12px;
  border-radius: 2px;
  font-size: 12px;
  min-width: 60px;
  text-align: center;
}

/* 主要状态 */
.record-status.primary {
  background: rgba(24, 144, 255, 0.1);
  color: #1890ff;
}

/* 成功状态 */
.record-status.success {
  background: rgba(82, 196, 26, 0.1);
  color: #52c41a;
}

/* 信息状态 */
.record-status.info {
  background: rgba(144, 147, 153, 0.1);
  color: #909399;
}

/* 警告状态 */
.record-status.warning {
  background: rgba(255, 152, 0, 0.1);
  color: #ff9800;
}

/* 危险状态 */
.record-status.danger {
  background: rgba(244, 67, 54, 0.1);
  color: #f44336;
}

.map-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

.theme-switch {
  position: fixed;
  top: 100px;
  right: 430px;
  z-index: 2000;
}

.theme-btn {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 40px;
  height: 40px;
  padding: 0;
}

:deep(.theme-btn .el-icon-sunny),
:deep(.theme-btn .el-icon-moon) {
  font-size: 20px;
}

/* 隐藏百度地图 logo */
::v-deep .anchorBL {
  display: none !important;
}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #102338;
}

::-webkit-scrollbar-thumb {
  background: #03A9F4;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #039BE5;
}

.locate-btn {
  position: fixed;
  top: 70px;
  right: 20px;
  z-index: 2000;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(30, 85, 120, 0.65);
  border: 1px solid #039BE5;
  color: #E1F5FE;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 0 15px rgba(3, 155, 229, 0.25);
}

.locate-btn:hover {
  background: rgba(30, 85, 120, 0.8);
  transform: scale(1.05);
  box-shadow: 0 0 20px rgba(3, 155, 229, 0.3);
}

.locate-btn i {
  font-size: 20px;
}
</style>